package com.bgi.cg.oss4j.common.util;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

import java.io.File;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @Description OSS文件上传通用处理
 * @Author Z.cg
 * @Date 2023/9/8
 * @Version 1.0
 **/
public class OssUtil {
    final static String HTTPS = "https://";
    final static String HTTP = "http://";
    final static String POINT_CHAR = ".";
    final static String MONTH_FORMAT = "yyyyMM";
    final static String SLASH = "/";

    public static String generatePath(File file) {
        return new StringBuilder(LocalDate.now().format(DateTimeFormatter.ofPattern(MONTH_FORMAT))).append(SLASH)
                .append(RandomUtil.randomString(32)).append(POINT_CHAR).append(FileNameUtil.getSuffix(file)).toString();
    }

    public static String getFileDomain(String fileDomain, String bucket) {
        if (StrUtil.containsIgnoreCase(fileDomain, HTTPS + bucket + POINT_CHAR)
                || StrUtil.containsIgnoreCase(fileDomain, HTTP + bucket + POINT_CHAR)) {
            return fileDomain;
        }
        if (StrUtil.startWithIgnoreCase(fileDomain, HTTPS)) {
            return StrUtil.replaceFirst(fileDomain, HTTPS, HTTPS + bucket + POINT_CHAR, false);
        }
        if (StrUtil.startWithIgnoreCase(fileDomain, HTTP)) {
            return StrUtil.replaceFirst(fileDomain, HTTP, HTTP + bucket + POINT_CHAR, false);
        }
        return bucket + POINT_CHAR + fileDomain;
    }

    public static String getRootFileName(String fileName) {
        if (fileName.startsWith(SLASH)) return fileName;
        return SLASH + fileName;
    }
}
